const express = require("express");
const router = express.Router();
const _ = require("lodash");
const path = require("path");
const dirname = path.resolve();
const { Storage, validateStorage } = require(path.join(
  dirname,
  "src/model/storage"
));
const { Mapping, validateMapping } = require(path.join(
  dirname,
  "src/model/mapping"
));

function handleEntityJSON(entity, fn) {
  const entityTemp = _.pick(entity, [
    "_id",
    "entityName",
    "description",
    "owners",
    "fields",
    "indexs",
  ]);
  entityTemp.fields = fn(entityTemp.fields);
  entityTemp.indexs = fn(entityTemp.indexs);
  return entityTemp;
}

function handleStorageJSON(storage) {
  const storageTemp = _.pick(storage, [
    "_id",
    "storageUri",
    "description",
    "idcInfos",
    "type",
    "owners",
  ]);
  storageTemp.idcInfos = JSON.parse(storageTemp.idcInfos);
  return storageTemp;
}

// 获取 storageUri 列表
router.get("/storageUri", async (req, res) => {
  req.query = _.pick(req.query, ["query", "type"]);
  const { query, type } = req.query;
  const queryReg = new RegExp(query, "gi");
  const typeReg = new RegExp(type, "gi");

  const storages = await Storage.find({
    storageUri: queryReg,
    type: typeReg,
  }).limit(10);

  const result = storages.map((item) => item.storageUri);
  res.send({ data: result, message: "获取 storageUri 成功" });
});

// 获取 storage 数据列表
router.get("/", async (req, res) => {
  req.query = _.pick(req.query, ["query", "type", "owner", "first", "number"]);
  const { query, type, owner } = req.query;

  const queryReg = new RegExp(query, "gi");
  const typeReg = new RegExp(type, "gi");
  const ownerReg = new RegExp(owner, "gi");

  const skip = req.query.first || 1;
  const limit = req.query.number || 100;

  const storages = await Storage.find({
    storageUri: queryReg,
    type: typeReg,
    owners: ownerReg,
  })
    .skip(skip - 1)
    .limit(limit)
    .sort({ modifyTime: -1 });

  const result = storages.map((item) => handleStorageJSON(item));
  res.send({ data: result, message: "获取 storage 成功" });
});

// 根据 storageUri 获取详细信息
router.get("/:storageUri", async (req, res) => {
  const storage = await Storage.findOne({ storageUri: req.params.storageUri });
  if (!storage) return res.status(400).send({ message: "该 storage 不存在" });
  res.send({
    data: handleStorageJSON(storage, JSON.parse),
    message: "获取 storage 成功",
  });
});

// 创建 storage
router.post("/add", async (req, res) => {
  // 校验格式
  req.body = _.pick(req.body, [
    "storageUri",
    "description",
    "idcInfos",
    "type",
    "owners",
  ]);
  req.body.idcInfos = JSON.stringify(req.body.idcInfos);
  const { error } = validateStorage(req.body);
  if (error) return res.status(400).send({ message: error.message });

  // 查询该storageUri是否存在
  const storage = await Storage.findOne({ storageUri: req.body.storageUri });
  if (storage) return res.status(400).send({ message: "该 storage 已经存在" });

  // 添加 storage
  await new Storage(req.body).save();
  res.send({
    message: "创建 storage 成功",
  });
});

// 根据 storageUri 修改 storage
router.put("/:storageUri", async (req, res) => {
  // 校验格式
  req.body = _.pick(req.body, [
    "storageUri",
    "description",
    "idcInfos",
    "type",
    "owners",
  ]);
  req.body.idcInfos = JSON.stringify(req.body.idcInfos);
  const { error } = validateStorage(req.body);
  if (error) return res.status(400).send({ message: error.message });

  // 查询该storageUri是否存在
  const storage = await Storage.findOne({ storageUri: req.body.storageUri });
  if (!storage) return res.status(400).send({ message: "该 storage 不存在" });

  // 编辑 storage
  await Storage.findByIdAndUpdate(
    storage._id,
    { $set: req.body },
    { useFindAndModify: false }
  );
  res.send({
    message: "编辑 storage 成功",
  });
});

// 根据 storageUri 删除 storage
router.delete("/:storageUri", async (req, res) => {
  // 查询该storageUri是否存在
  const storage = await Storage.findOne({ storageUri: req.params.storageUri });
  if (!storage) return res.status(400).send({ message: "该 storage 不存在" });

  // 编辑 storage
  await Storage.findByIdAndDelete(storage._id);
  res.send({
    message: "删除 storage 成功",
  });
});

module.exports = router;
